<?php

/**
 * alltosun.com oauth2.0授权类控制器 AnAuthorizeV2.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: liww $
 * $Date: 2012-8-7 下午09:41:59 $
 * $Id: AnAuthorizeV2.php 103353 2012-09-21 07:54:40Z liww $
*/

// if (SAE) {
//     require_once 'saetv2.ex.class.php';
// } else {
//     require_once MODULE_PATH.'/openapi/helper/saetv2.ex.class.php';
// }

// 把类名改了,添加了quick_auth参数，
require_once MODULE_PATH.'/openapi/helper/saetv2.ex.class.php';

class AnAuthorizeV2
{
    private $akey;
    private $skey;
    private $callback;
    private $o;
    private $code;
    private $site_name;
    private $site_id;
    private $user_id;

    public function __construct($code = '')
    {
        $this->akey = Config::get('sinaweibo_akey');
        $this->skey = Config::get('sinaweibo_skey');
        $this->callback = Config::get('sinaweibo_callback');
        //var_dump($this->callback);
        $this->code = $code;
        $this->site_name = 'sinaweibo';
        $this->site_id = 1;
        $this->o = new SaeTOAuthV2LOCAL($this->akey, $this->skey);
        $this->user_id = user_helper::get_user_id();
        if (!$this->user_id && ONDEV) {
            $this->user_id = 100002;
        }
    }

    public function authorize()
    {
        //$_SESSION['user_id'] = 0;

        //var_dump($this->callback, 11);
        //$code_url = $this->o->getAuthorizeURL($this->callback);
        //$code_url = $this->o->getAuthorizeURL($this->callback, 'code', NULL, 'mobile');

        //var_dump($code_url);exit;
        //Response::redirect($code_url);

        $connect_info = array();
        if ($this->user_id) {
            $connect_info = _uri('connect', array('user_id'=>$this->user_id, 'connect_site_id'=>$this->site_id));
        }

        if ($connect_info) {
            // 判断access_token是否过期
            if (time() > $connect_info['expires_time']) {
                // 刷新access_token
                $code_url = $this->o->getAuthorizeURL($this->callback, 'code', NULL, 'mobile');
                //var_dump($code_url);
                Response::redirect($code_url);
            } else {
                $_SESSION[$this->site_name]['token']['access_token'] = $connect_info['access_token'];
                $_SESSION[$this->site_name]['token']['connect_user_id'] = $connect_info['connect_user_id'];

                Response::redirect(AnUrl('lottery/m/runfa/send_weibo'));
                //$this->close_auth();
                //                     Response::redirect(SITE_URL);
            }
        } else {
            $code_url = $this->o->getAuthorizeURL($this->callback, 'code', NULL, 'mobile');
            $code_url = str_replace('+', '', $code_url);
            Response::redirect($code_url);
        }
    }

    public function callback()
    {
        //var_dump($this->code);
        if (!$this->code) {
            $error = Request::Get('error', '');
            if ($error == 'access_denied') {
                self::close_auth();
                return;
            } else {
                self::auth_fail('授权失败');
                return;
            }
        }
        $keys = array();
	    $keys['code'] = $this->code;
    	$keys['redirect_uri'] = $this->callback;

    	//var_dump($keys);
    	try {
    		$token = $this->o->getAccessToken('code', $keys);
    	} catch (OAuthExceptionLOCAL $e) {
    	}

    	//var_dump($token);

    	if ($token) {
        	$c = new SaeTClientV2LOCAL($this->akey, $this->skey, $token['access_token']);
        	$get_uid = $c->get_uid();
            if (empty($get_uid) || empty($get_uid['uid'])) {
                if (isset($get_uid['error_code']) && $get_uid['error_code'] == '21321') {
                    self::auth_fail('您的ID没有权限，请联系管理员添加测试账号');return;
                } else {
                    self::auth_fail('授权失败');return;
                }
//                 throw new Exception('授权失败，未获取到uid');
            }

        	$_SESSION[$this->site_name]['token'] = $token;
        	$_SESSION[$this->site_name]['token']['connect_user_id'] = $get_uid['uid'];


        	$connect_info = _uri('connect', array('connect_user_id'=>$get_uid['uid'], 'connect_site_id'=>$this->site_id));
        	if (!$connect_info) {
        	    $weibo_info = AnSinaWeiboV2::getUserInfoById($get_uid['uid']);
        	    // 新用户处理，如果不在user表中则保存，在的话直接返回。
        	    //user_helper::save_new_user($get_uid['uid'], $weibo_info);
        	    $user_id = user_helper::bind_weibo_user($get_uid['uid'], $weibo_info);


        	    // 保存授权信息
                $connect_info = array(
                    'user_id'         => $user_id,
                    'connect_user_id' => $get_uid['uid'],
                    'connect_site_id' => 1,
                    'user_name'       => $weibo_info['screen_name'],
                    'access_token'    => $token['access_token'],
//                     'appkey' => $this->akey,
//                    'refresh_token' => $token['refresh_token'],
                    'expires_time' => $token['expires_in']+time()
                );
                $connect_id = _model('connect')->create($connect_info);
        	} else {
                _model('connect')->update($connect_info['id'], array('access_token'=>$token['access_token'], 'expires_time'=>$token['expires_in']+time()));
        	}
        	$_SESSION['user_id'] = $connect_info['user_id'];
        	Response::redirect(AnUrl('lottery/m/runfa/send_weibo'));
        	//self::auth_succ();
    	} else {
    	    Response::redirect(AnUrl('openapi/session_op/clear_session'));
    	}
    }

    /**
     * 点击取消关闭授权浮层
     */
    private function close_auth()
    {
        echo <<<END
    <script type="text/javascript">
    parent.closeAuth();
    </script>
END;
    }
    /**
     * 授权失败
     */
    private function auth_fail($msg='授权失败')
    {
        echo <<<END
    <script type="text/javascript">
      parent.authFail('{$msg}');
    </script>
END;
    }
    /**
     * 授权成功
     */
    private function auth_succ()
    {
        echo <<<END
    <script type="text/javascript">
      var userId = {$_SESSION['user_id']};
      var param = {'id':userId, 'needAuth':0};
      parent.authSucc(param);
    </script>
END;
    }
}
?>